package data_structure.mooc.filereader;

import data_structure.mooc.AVLTree;
import data_structure.mooc.RABTree;

import javax.print.DocFlavor;
import java.io.*;
import java.util.ArrayList;

public class FileReader {


    public  static boolean readFile(String filename, ArrayList<String> words){

        File file=new File(filename);
        if(file.exists()){
            try {
                InputStream inputStream=new FileInputStream (file);
                BufferedReader reader = new BufferedReader(new InputStreamReader (inputStream));
                while((reader.readLine())!=null){
                    String line=reader.readLine();
                    letter(line,words);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace ();
            } catch (IOException e) {
                e.printStackTrace ();
            }
        }else{
            return false;
        }
        return true;
    }

    private static void letter(String line, ArrayList<String> words) {
        String word;
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<line.length ();i++){
            if(line.charAt (i)>='a'&&line.charAt (i)<='z'||line.charAt (i)>='A'&&line.charAt (i)<='Z') {
                sb.append (line.charAt (i));
            }else if(line.charAt(i) ==' '){
                if(i-1>=0&&((line.charAt (i-1)>='a'&&line.charAt (i-1)<='z')||(line.charAt (i-1)>='A'&&line.charAt (i-1)<='Z'))){
                    word=sb.toString ();
                    words.add (word);
                    sb.setLength (0);
                }
            }else{
                //处理符号
                word=sb.toString ();
                words.add (word);
                sb.setLength (0);
            }
        }
    }

    public static void main(String[] args) {
        ArrayList<String> words = new ArrayList<String> ();
        boolean o = readFile ("D:\\datastructure\\src\\data_structure\\mooc\\filereader\\hamlet.txt", words);

        System.out.println(words.size ());
//        AVLTree<String,Integer> tree = new AVLTree<String, Integer>();
        RABTree<String,Integer>tree=new RABTree<String, Integer> ();
        for(String string:words){
            if(tree.contains (string)){
               tree.set (string,tree.get(string)+1);
            }else{
                tree.add(string,1);
            }
        }
        System.out.println(tree.getSize ());
        System.out.println(tree);
    }
}
